<?php


namespace app\phIndex\controller;


use app\model\ModelTask;
use app\model\ModelUser;
use app\model\ModelUserTask;
use app\phindex\phpqrcode\QRimage;
use app\phIndex\service\Service;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class Index extends Service
{
    public function index(): string
    {
        $this->is_login();
        $userId = $this->getLoginUserId();
        $this->assign('name', 'sank');
        $this->assign('userId', $userId);
        return $this->fetch('index:index');
    }

    public function login(): string
    {
        $mobile = input('mobile');
        $password = md5(input('password'));

        if ($mobile) {
            if($this->checkPassword($mobile, $password)) {
                session('user', $mobile);
                cookie('currentUser', $mobile, 3600);
                $this->loginTime();
                redirect(url('index'))->send();
                return '登录成功 '.session($mobile);
            }else {
                return '用户名或密码错误';
            }

        } else {
            return $this->fetch('index:login');
        }
    }

    public function logout()
    {
        session('user', null);
        cookie('currentUser', null);
        redirect(url('login'))->send();
    }

    /**
     * 下载APP页面
     * @return string
     * @throws \Exception
     */
    public function downLoadApp(): string
    {
        return $this->fetch('index:downLoadApp');
    }


    /**
     * 当前用户领取任务
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getTask() {
        $taskId = input('id');
        $userId = $this->getLoginUserId();
        $userTask = new ModelUserTask();
        $task = new ModelTask();
        $taskInfo = $task->where(['id' => $taskId])->find();
        $task->where(['id' => $taskId])->update([
            'task_complete' => $taskInfo['task_complete'] + 1
        ]);
        if($taskInfo['task_complete'] + 1 == $taskInfo['task_total']) {
            $task->where(['id' => $taskId])->save(
                ['task_status' => 1]
            );
        }
        $userTask->insert([
            'user_id' => $userId,
            'task_id' => $taskId,
            'task_start_time' => time(),
            'task_status' => 1
        ]);
        redirect(url('index'))->send();
    }

    /**
     * 当前用户已领取任务
     * @return string
     * @throws \Exception
     */
    public function myTask(): string
    {
        $this->is_login();
        $userId = $this->getLoginUserId();
        if(empty($userId)) redirect(url('login'))->send();
        $this->assign('userId', $userId);
        return $this->fetch('index:myTask');
    }

    /**
     * 更新任务状态
     */
    public function reviewTask() {
        $userId = input('userId');
        $taskId = input('taskId');
        $userTaskModel = new ModelUserTask();
        $userTaskModel->where([
            'user_id' => $userId,
            'task_id' => $taskId
        ])->save([
            'task_status' => 2
        ]);
        redirect(url('myTask'))->send();
    }

    public function  test() {
        $arr = [
            ['a'=>1],
            ['a'=>2],
        ];
        foreach($arr as &$val){
            $val['b'] = 3;
            $val['c'] = 4;
            $val['d'] = 5;
            $val['e'] = 6;
        }
        return json($arr);
    }


    // 1. 生成原始的二维码(生成图片文件)
    function scerweima(){
        $value=['www.baid.com'];      //二维码内容
        $errorCorrectionLevel = 4;  //容错级别
        $matrixPointSize = 5;      //生成图片大小
        //生成二维码图片
        $filename = '/qrcode/1.png';
        QRcode::jpg($value,$filename , $errorCorrectionLevel, $matrixPointSize, 2);
        $QR = $filename;        //已经生成的原始二维码图片文件
        $QR = imagecreatefromstring(file_get_contents($QR));
        //输出图片
        imagepng($QR, 'qrcode.png');
        imagedestroy($QR);
        return '<img src="qrcode.png" alt="使用微信扫描支付">';
    }


    //2. 在生成的二维码中加上logo(生成图片文件)
    function scerweima1(){
        $url=['www.baid.com'];
//        require_once '../';
        $value = $url;         //二维码内容
        $errorCorrectionLevel = 4;  //容错级别
        $matrixPointSize = 6;      //生成图片大小
        //生成二维码图片
        $filename = $_SERVER['DOCUMENT_ROOT'].'/qrcode/'.date("Ymd").'.png';
        QRimage::png($value,$filename , $errorCorrectionLevel, $matrixPointSize, TRUE);
        $logo = $_SERVER['DOCUMENT_ROOT'].'/qrcode/logo.jpg'; //准备好的logo图片
        $QR = $filename;      //已经生成的原始二维码图
        if (file_exists($logo)) {
            $QR = imagecreatefromstring(file_get_contents($QR));    //目标图象连接资源。
            $logo = imagecreatefromstring(file_get_contents($logo));  //源图象连接资源。
            $QR_width = imagesx($QR);      //二维码图片宽度
            $QR_height = imagesy($QR);     //二维码图片高度
            $logo_width = imagesx($logo);    //logo图片宽度
            $logo_height = imagesy($logo);   //logo图片高度
            $logo_qr_width = $QR_width / 4;   //组合之后logo的宽度(占二维码的1/5)
            $scale = $logo_width/$logo_qr_width;  //logo的宽度缩放比(本身宽度/组合后的宽度)
            $logo_qr_height = $logo_height/$scale; //组合之后logo的高度
            $from_width = ($QR_width - $logo_qr_width) / 2;  //组合之后logo左上角所在坐标点
            //重新组合图片并调整大小
            /*
             * imagecopyresampled() 将一幅图像(源图象)中的一块正方形区域拷贝到另一个图像中
             */
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height);
        }
        //输出图片
        imagepng($QR, 'qrcode.png');
        imagedestroy($QR);
        imagedestroy($logo);
        echo '<img src="qrcode.png" alt="使用微信扫描支付">';
    }


}